Java Programming Language
Java Exception Handling Exercises

These exercises are designed to evaluate your knowledge, comprehension, application, analysis and synthesis of the Java exception handling syntax and structure. It is expected that you should be able to correctly answer all or nearly all of the questions and problems presented. You should do these exercises by yourself.

1. When should you throw exceptions up and when should you catch and deal with them?

 

 

2. How would you catch an exception, do some recovery but not all and then pass the exception up to the parent object?

 

 

3. Explain the difference between an Error and an Exception and how these relate to Checked and Unchecked exceptions.

 

 

4. List and explain the five exception handling syntax clauses.

 

 

5. Given the code fragment below, describe the flow of execution for each of the scenarios listed once the checkFuel() method is executed.

public static void main(String args[]) throws IOException
{
String msg = "";

do
{
	try
	{
		checkFuel();
	}
	catch (SparksDetected e)
	{
		msg = "Sparks in fuel tank!";
		break;
	}
	catch (FuelClog e)
	{
		msg = "Fuel clog";
		System.exit();
	}
	catch (OutOfFuel e)
	{
		msg = "out of fuel";
		sendSOS();
	}
	catch (FuelLow e)
	{
		msg = "fuel low";
	}
	catch (UnreadableResponse)
	{
		msg = "can’t determine fuel level";
		throw new IOException(msg);
	}
	finally
	{
		informPilot(msg);
	}
} while (true);

	crashLand();

}
  1. OutOfFuel exception encountered.
  2. UnreadableResponse exception encountered.
  3. FuelClog exception encountered.
  4. FuelLow exception encountered.
  5. No exception encountered.
  6. SparksDetected exception ecountered.

 

6. How does the exception object hierarchy relate to the catch clauses?

 

 

7. What is wrong with the following code fragment?

Exception hierarchy:

Object -> Throwable -> Exception -> IOException -> FileNotFoundException

try
{
	fileIn = new BufferedReader(new FileReader("data.txt"));
}
catch (IOException e)
{
	System.out.println("ERROR: "+e.getMessage());
	System.exit(1);
}
catch (FileNotFoundException e)
{
	System.out.println("ERROR: "+e.getMessage());
	System.exit(1);
}